package com.demo.java.disruptor.netty.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.jboss.marshalling.ByteInputStream;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

// 消息解码
public class MessageDecode extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf msg, List<Object> list) throws Exception {
        int length = msg.readableBytes();
        if (length >= 4) {
            byte[] objBytes = new byte[length];
            /*if (msg.hasArray()) {
                int readIndex = msg.readerIndex();
                msg.skipBytes(msg.arrayOffset() + readIndex);
                msg.readBytes(objBytes, 0, length);
            } else {
            }*/
            msg.readBytes(objBytes);

            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(objBytes));
            Object obj = ois.readObject();
            list.add(obj);
            ois.close();
//            msg.skipBytes(length);
        }

    }
}
